#include "controller.h"

Controller::Controller() : nameTest("")
{
    mainWin = new MainWindow();
    mainWin->setWindowTitle("OpenCV --> QtImage");
    mainWin->show();

//    timer = new TimerTest(timeDisplay);
    config = new Config(mainWin);

//    imageSize = QSize(160,120);
    imageSize = QSize(640,480);
//    imageSize = QSize(1280,720);
//    imageSize = QSize(1920,1080);

    cam = new CamManager(imageSize);
    cam->start();

    record = new Record(imageSize, QString("VideoDeTest.avi"));
    videoDisplay = new Video(imageSize);
    inquiry = new Inquiry();

    connect(mainWin, SIGNAL(testLaunched()), this, SLOT(launchTest()));
    connect(mainWin, SIGNAL(testStopped()), this, SLOT(stopTest()));
    connect(mainWin, SIGNAL(butVideoClicked()), this, SLOT(displayVideo()));
    connect(mainWin, SIGNAL(closed()), qApp, SLOT(quit()));
    connect(videoDisplay, SIGNAL(closed()), this, SLOT(displayVideo()));
    connect(this, SIGNAL(close()), qApp, SLOT(quit()));

    displayedVideo = false;

    qDebug() << "____________________________________________Controller :   " << QThread::currentThreadId();
}

Controller::~Controller()
{
    cam->~CamManager();
    record->~Record();
    videoDisplay->~Video();
    inquiry->~Inquiry();
}

void Controller::launchTest()
// Lance le test
{
    if(nameTest.isEmpty()){
        nameTest = QDateTime::currentDateTime().toString();
        record->setNameTest(nameTest);
        inquiry->setNameTest(nameTest);
    }
    cam->registerConsumer(record);
    cam->registerConsumer(inquiry);
    record->start();
    inquiry->start();
}

void Controller::stopTest()
// Termine le test precedemment lance
{
    record->terminate();
    inquiry->terminate();
    cam->removeConsumer(record);
    cam->removeConsumer(inquiry);
}

void Controller::displayVideo()
// Affiche ou cache une fenetre diffusant le flux de la camera
{
//    cam->registerConsumer(inquiry);

    if (!displayedVideo){
        cam->registerConsumer(videoDisplay);
        videoDisplay->run();
//        emit showVideo();
    }
    else{
        videoDisplay->terminate();
        cam->removeConsumer(videoDisplay);
    }
    displayedVideo = !displayedVideo;
}
